package com.example.a_java.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.a_java.common.BusinessException;
import com.example.a_java.dto.CustomerDTO;
import com.example.a_java.dto.CustomerQueryDTO;
import com.example.a_java.dto.CustomerStatusDTO;
import com.example.a_java.dto.CustomerVisitDTO;
import com.example.a_java.entity.CustExtendInfo;
import com.example.a_java.entity.CustInfo;
import com.example.a_java.entity.CustVisitRecord;
import com.example.a_java.mapper.CustExtendInfoMapper;
import com.example.a_java.mapper.CustInfoMapper;
import com.example.a_java.mapper.CustVisitRecordMapper;
import com.example.a_java.mapper.LoanMapper;
import com.example.a_java.service.CustomerService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客户管理Service实现
 */
@Service
@RequiredArgsConstructor
public class CustomerServiceImpl implements CustomerService {

    private final CustInfoMapper custInfoMapper;
    private final CustExtendInfoMapper custExtendInfoMapper;
    private final CustVisitRecordMapper custVisitRecordMapper;
    private final LoanMapper loanMapper;
    
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public IPage<CustomerDTO> listCustomers(CustomerQueryDTO query) {
        Page<CustomerDTO> page = new Page<>(query.getPageNum(), query.getPageSize());
        return custInfoMapper.selectCustomerList(page, query);
    }

    @Override
    public CustomerDTO getCustomerById(Long custId) {
        CustomerDTO customerDTO = custInfoMapper.selectCustomerById(custId);
        if (customerDTO == null) {
            throw new BusinessException("客户不存在");
        }
        
        // 查询客户扩展信息
        CustExtendInfo extendInfo = custExtendInfoMapper.selectOne(
                new LambdaQueryWrapper<CustExtendInfo>()
                        .eq(CustExtendInfo::getCustId, custId)
        );
        
        if (extendInfo != null) {
            Map<String, Object> extendMap = new HashMap<>();
            extendMap.put("occupation", extendInfo.getOccupation());
            extendMap.put("company", extendInfo.getCompany());
            extendMap.put("annualIncome", extendInfo.getAnnualIncome());
            extendMap.put("education", extendInfo.getEducation());
            extendMap.put("maritalStatus", extendInfo.getMaritalStatus());
            customerDTO.setExtendInfo(extendMap);
        }
        
        return customerDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addCustomer(CustomerDTO customerDTO) {
        // 转换并保存客户基本信息
        CustInfo custInfo = new CustInfo();
        custInfo.setCustName(customerDTO.getName());
        custInfo.setMobile(customerDTO.getPhone());
        custInfo.setIdType("ID_CARD".equals(customerDTO.getIdType()) ? 1 : 2); // 简化处理，实际应根据字典转换
        custInfo.setIdNo(customerDTO.getIdCard());
        custInfo.setCustType("personal".equals(customerDTO.getType()) ? 1 : 2);
        custInfo.setEmail(customerDTO.getEmail());
        custInfo.setAddress(customerDTO.getAddress());
        custInfo.setStatus(customerDTO.getStatus() != null ? customerDTO.getStatus() : 1);
        custInfo.setRemark(customerDTO.getRemark());
        
        custInfoMapper.insert(custInfo);
        
        // 保存扩展信息
        if (customerDTO.getExtendInfo() != null && !customerDTO.getExtendInfo().isEmpty()) {
            CustExtendInfo extendInfo = new CustExtendInfo();
            extendInfo.setCustId(custInfo.getCustId());
            extendInfo.setGender(customerDTO.getGender());
            extendInfo.setAge(customerDTO.getAge());
            
            Map<String, Object> extendMap = customerDTO.getExtendInfo();
            extendInfo.setOccupation((String) extendMap.get("occupation"));
            extendInfo.setCompany((String) extendMap.get("company"));
            extendInfo.setEducation((String) extendMap.get("education"));
            extendInfo.setMaritalStatus((String) extendMap.get("maritalStatus"));
            
            // 处理年收入
            Object annualIncome = extendMap.get("annualIncome");
            if (annualIncome != null) {
                if (annualIncome instanceof Number) {
                    extendInfo.setAnnualIncome(java.math.BigDecimal.valueOf(((Number) annualIncome).doubleValue()));
                } else if (annualIncome instanceof String) {
                    extendInfo.setAnnualIncome(new java.math.BigDecimal((String) annualIncome));
                }
            }
            
            custExtendInfoMapper.insert(extendInfo);
        }
        
        return custInfo.getCustId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCustomer(CustomerDTO customerDTO) {
        if (customerDTO.getId() == null) {
            throw new BusinessException("客户ID不能为空");
        }
        
        // 检查客户是否存在
        CustInfo existingCustomer = custInfoMapper.selectById(customerDTO.getId());
        if (existingCustomer == null) {
            throw new BusinessException("客户不存在");
        }
        
        // 更新客户基本信息
        CustInfo custInfo = new CustInfo();
        custInfo.setCustId(customerDTO.getId());
        custInfo.setCustName(customerDTO.getName());
        custInfo.setMobile(customerDTO.getPhone());
        custInfo.setIdType("ID_CARD".equals(customerDTO.getIdType()) ? 1 : 2);
        custInfo.setIdNo(customerDTO.getIdCard());
        custInfo.setCustType("personal".equals(customerDTO.getType()) ? 1 : 2);
        custInfo.setEmail(customerDTO.getEmail());
        custInfo.setAddress(customerDTO.getAddress());
        custInfo.setRemark(customerDTO.getRemark());
        
        custInfoMapper.updateById(custInfo);
        
        // 更新扩展信息
        if (customerDTO.getExtendInfo() != null) {
            // 查询是否已存在扩展信息
            CustExtendInfo existingExtendInfo = custExtendInfoMapper.selectOne(
                    new LambdaQueryWrapper<CustExtendInfo>()
                            .eq(CustExtendInfo::getCustId, customerDTO.getId())
            );
            
            CustExtendInfo extendInfo = existingExtendInfo != null ? existingExtendInfo : new CustExtendInfo();
            if (existingExtendInfo == null) {
                extendInfo.setCustId(customerDTO.getId());
            }
            
            extendInfo.setGender(customerDTO.getGender());
            extendInfo.setAge(customerDTO.getAge());
            
            Map<String, Object> extendMap = customerDTO.getExtendInfo();
            extendInfo.setOccupation((String) extendMap.get("occupation"));
            extendInfo.setCompany((String) extendMap.get("company"));
            extendInfo.setEducation((String) extendMap.get("education"));
            extendInfo.setMaritalStatus((String) extendMap.get("maritalStatus"));
            
            // 处理年收入
            Object annualIncome = extendMap.get("annualIncome");
            if (annualIncome != null) {
                if (annualIncome instanceof Number) {
                    extendInfo.setAnnualIncome(java.math.BigDecimal.valueOf(((Number) annualIncome).doubleValue()));
                } else if (annualIncome instanceof String) {
                    extendInfo.setAnnualIncome(new java.math.BigDecimal((String) annualIncome));
                }
            }
            
            if (existingExtendInfo != null) {
                custExtendInfoMapper.updateById(extendInfo);
            } else {
                custExtendInfoMapper.insert(extendInfo);
            }
        }
        
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCustomers(String custIds) {
        if (!StringUtils.hasText(custIds)) {
            throw new BusinessException("客户ID不能为空");
        }
        
        String[] ids = custIds.split(",");
        // 删除客户基本信息
        Arrays.stream(ids).forEach(id -> {
            Long custId = Long.parseLong(id);
            custInfoMapper.deleteById(custId);
            
            // 删除扩展信息
            custExtendInfoMapper.delete(
                    new LambdaQueryWrapper<CustExtendInfo>()
                            .eq(CustExtendInfo::getCustId, custId)
            );
            
            // 删除回访记录
            custVisitRecordMapper.delete(
                    new LambdaQueryWrapper<CustVisitRecord>()
                            .eq(CustVisitRecord::getCustId, custId)
            );
        });
        
        return true;
    }

    @Override
    public boolean updateCustomerStatus(CustomerStatusDTO statusDTO) {
        if (statusDTO.getCustId() == null) {
            throw new BusinessException("客户ID不能为空");
        }
        
        CustInfo custInfo = new CustInfo();
        custInfo.setCustId(statusDTO.getCustId());
        custInfo.setStatus(statusDTO.getStatus());
        
        return custInfoMapper.updateById(custInfo) > 0;
    }

    @Override
    public IPage<CustomerVisitDTO> listVisitRecords(Long custId, Integer pageNum, Integer pageSize) {
        if (custId == null) {
            throw new BusinessException("客户ID不能为空");
        }
        
        Page<CustomerVisitDTO> page = new Page<>(pageNum, pageSize);
        return custVisitRecordMapper.selectVisitList(page, custId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addVisitRecord(CustomerVisitDTO visitDTO) {
        if (visitDTO.getCustId() == null) {
            throw new BusinessException("客户ID不能为空");
        }
        
        // 检查客户是否存在
        CustInfo custInfo = custInfoMapper.selectById(visitDTO.getCustId());
        if (custInfo == null) {
            throw new BusinessException("客户不存在");
        }
        
        CustVisitRecord visitRecord = new CustVisitRecord();
        visitRecord.setCustId(visitDTO.getCustId());
        visitRecord.setVisitTime(LocalDateTime.parse(visitDTO.getVisitTime(), DATE_TIME_FORMATTER));
        visitRecord.setMethod(visitDTO.getMethod());
        visitRecord.setVisitor(visitDTO.getVisitor());
        visitRecord.setContent(visitDTO.getContent());
        visitRecord.setFeedback(visitDTO.getFeedback());
        
        if (StringUtils.hasText(visitDTO.getNextVisitTime())) {
            visitRecord.setNextVisitTime(LocalDateTime.parse(visitDTO.getNextVisitTime(), DATE_TIME_FORMATTER));
        }
        
        custVisitRecordMapper.insert(visitRecord);
        return visitRecord.getVisitId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteVisitRecords(String visitIds) {
        if (!StringUtils.hasText(visitIds)) {
            throw new BusinessException("回访记录ID不能为空");
        }
        
        String[] ids = visitIds.split(",");
        Arrays.stream(ids).forEach(id -> {
            custVisitRecordMapper.deleteById(Long.parseLong(id));
        });
        
        return true;
    }

    @Override
    public IPage<Map<String, Object>> listCustomerLoans(Long custId, Integer pageNum, Integer pageSize, String status) {
        if (custId == null) {
            throw new BusinessException("客户ID不能为空");
        }
        
        Page<Map<String, Object>> page = new Page<>(pageNum, pageSize);
        return loanMapper.selectCustomerLoanList(page, custId, status);
    }

    @Override
    public Map<String, Object> getLoanById(Long loanId) {
        if (loanId == null) {
            throw new BusinessException("贷款ID不能为空");
        }
        
        Map<String, Object> loanDetail = loanMapper.selectLoanDetail(loanId);
        if (loanDetail == null) {
            throw new BusinessException("贷款记录不存在");
        }
        
        return loanDetail;
    }
} 
